package com.lushu.helpers.structure {
import com.lushu.data.interfaces.ITreeProvider;

import flash.events.EventDispatcher;

public class TreeNode extends EventDispatcher {
    private var children_:Vector.<TreeNode>;
    private var name_:String
    private var data_:ITreeProvider;
    private var dataIndex_:int;
    private var isLeaf_:Boolean;

    public function TreeNode(label:String) {
        name_ = label;
        children_ = new Vector.<TreeNode>();
        isLeaf_ = false;
    }

    public function getName():String {
        return name_;
    }

    public function getChildByName(name:String):TreeNode {
        var treeNode:TreeNode;
        var child:TreeNode;
        for (var i:int = 0; i < children_.length; i++) {
            treeNode = children_[i];
            if (treeNode.getName() == name)
                return treeNode;
            else {
                child = treeNode.getChildByName(name);
                if (child != null)
                    return child;
            }
        }
        return null;
    }

    public function addChild(node:TreeNode):void {
        children_.push(node);
    }

    public function setData(image:ITreeProvider):void {
        data_ = image;
        isLeaf_ = true;
    }

    public function getData():ITreeProvider {
        return data_;
    }

    public function write():XML {
        var xml:XML;
        if (!isLeaf_) {
            if (name_ == "root")
                xml = new XML("<root></root>");
            else if (data_ != null)
                xml = new XML('<rep label="' + name_ + '" data="' + data_.getName() + '"></rep>');
            else
                xml = new XML('<rep label="' + name_ + '" data="' + name_ + '"></rep>');
        }
        else {
            xml = new XML('<leaf label="' + name_ + '" data="' + data_.getName() + '"></leaf>');
        }
        var subXML:XML;
        if (!isLeaf_) {
            for (var i:int = 0; i < children_.length; i++) {
                subXML = children_[i].write();
                xml.appendChild(subXML);
            }
        }
        return xml;
    }
}
}